<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Index
 *
 * @author ananda
 */
class Action_Controller_Create extends Action
{
    public function main()
    {
        $this->controller->checkEnv();

        // 整理数据
        if (!isset($this->params[0])) {
            throw new Exception_Console('controller:param_lost_controller_to_create');
        }
        $controller = ucfirst($this->params[0]);
        $daction = isset($this->params[1]) ? ucfirst($this->params[1]) : 'Index';
        unset($this->params[0]);
        unset($this->params[1]);

        // 生成控制器
        $this->createControllerFile($controller, $daction);

        // 生成ACTION目录
        $this->createActionDir($controller);

        // 生成ACTION
        //$action = $this->callAction('Action', 'Create');

        echo Com::glob()->t['msg.controller:create_ok'];
    }

    public function createControllerFile($name, $daction)
    {
        // 判断文件是否存在
        $filename = $this->controller->getControllerDir()."$name.php";
        if (file_exists($filename)) {
            throw new Exception_Console('controller:controller_is_exists', 0, array($name));
        }

        // 生成ACTION列表和Action方法
        $action_list   = array("        '$daction'=>1,");
        foreach ($this->params as $action) {
            $action = ucfirst($action);
            $action_list[] = "        '$action'=>1,";
        }
        $action_list = implode("\n", $action_list);

        $script = <<<EOT
<?php
/**
 * Description
 *
 * @author 
 */
class Controller_$name extends Controller
{
    public \$self_name      = '$name';
    public \$action_list    = array(
$action_list
    );
    public \$action_default = '$daction';

    public function init() {}
}

EOT;
        file_put_contents($filename, $script);

        return true;
    }

    public function createActionDir($controller)
    {
        $pathname = $this->controller->getActionDir($controller);
        if (file_exists($pathname)) {
            return false;
        }
        mkdir($pathname, 0755, true);
        return true;
    }

}
